package com.prim.update.impl;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.prim.update.interfaces.IUpdateExplorer;
import com.prim.update.interfaces.IUpdateFile;
import com.prim.update.patch.PatchUtils;
import com.prim.update.utils.ApkUtils;
import com.prim.update.utils.FileUtils;

import java.io.File;
import java.lang.ref.WeakReference;

import cn.coolspan.open.IncrementUpdateLibs.IncrementUpdateUtil;


/**
 * ================================================
 * 作    者：linksus
 * 版    本：1.0
 * 创建日期：3/6 0006
 * 描    述：对下载完的文件进行检查处理操作的实现者
 * 修订历史：
 * ================================================
 */
public class UpdateFiler implements IUpdateFile {

    private WeakReference<Context> mContext;

    private static final String TAG = "UpdateFiler";

    public UpdateFiler(Context mContext) {
        this.mContext = new WeakReference<>(mContext);
    }

    @Override
    public void checkFile(IUpdateExplorer explorer) {
        boolean patch = explorer.getInfo().isPatch();
        if (explorer.getBuilder().isPatchUpdate) {//增量更新
//            int bspatch = PatchUtils.bspatch(FileUtils.sourceApkPath(mContext.get()), explorer.getPatchNewApkPath(),
//                    new File(Environment.getExternalStorageDirectory(), "to.patch").getAbsolutePath());
            int bspatch = IncrementUpdateUtil.bspatch(FileUtils.sourceApkPath(mContext.get()), explorer.getPatchNewApkPath(),
                    new File(Environment.getExternalStorageDirectory(), "to.patch").getAbsolutePath());
            Log.e(TAG, "checkFile: bspatch -->  " + bspatch);
            if (bspatch == 0) {
                ApkUtils.installApk(mContext.get(), explorer.getPatchNewApkPath());
            }
            return;
        }
        if (!patch) {//全量更新
            /** 此处检查apk文件的逻辑根据业务需求修改 也可以根据MD5 判断是否完整 */
            if (explorer.isApkCompleteExits()) {// 检查安装包是否存在且安装包是否完整
                ApkUtils.installApk(mContext.get(), explorer.getDownloadPath());
            }
        } else {// 增量更新
            if (explorer.getBuilder().isPatchUpdate) {// 允许增量更新
                patchUpdate(explorer);
            } else {
                explorer.stop();
            }
        }
    }

    private void patchUpdate(IUpdateExplorer explorer) {
//        int bspatch = PatchUtils.bspatch(FileUtils.sourceApkPath(mContext.get()), explorer.getDownloadPath(), explorer.getPatchNewApkPath());
//        if (bspatch == 0) {
//            ApkUtils.installApk(mContext.get(), explorer.getPatchNewApkPath());
//        } else {
//
//        }
    }


}
